﻿/*
This file is part of Claymore.
Copyright (C) 2010, Fabrice Michellonet (fabrice dot michellonet at gmail dot com)

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

using System;
using System.Collections.Generic;
using System.Reflection;

namespace Claymore
{
    public partial class ClaymorePresenterManager : IPresenterManager
    {

        #region Fields

        protected Dictionary<Type, Type> _viewType2PresenterType;
        protected Dictionary<Type, object> _viewType2IPresenter;
        
        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="ClaymorePresenterManager"/> class.
        /// </summary>
        public ClaymorePresenterManager()
        {
            _viewType2PresenterType = new Dictionary<Type, Type>();
            _viewType2IPresenter = new Dictionary<Type, object>();
        }

        /// <summary>
        /// Gets the presenter based on the implemented View interface it controls.
        /// </summary>
        /// <typeparam name="TIView">The type of the view interface.</typeparam>
        /// <returns></returns>
        public virtual IPresenter<TIView> GetPresenterFor<TIView>() where TIView : class, IView
        {
            Type viewType = typeof(TIView);

            if(!_viewType2IPresenter.ContainsKey(viewType))
                return null;

            return (IPresenter<TIView>) _viewType2IPresenter[viewType];
        }

        /// <summary>
        /// Adds the presenters assembly.
        /// </summary>
        /// <param name="asm">The asm.</param>
        public virtual void AddPresentersAssembly(Assembly asm)
        {
            foreach (Type type in asm.GetTypes())
            {
                if (type.BaseType != null)
                {
                    Type[] args = type.BaseType.GetGenericArguments();
                    if (args.Length == 1 && typeof (IPresenter<>).MakeGenericType(args).IsAssignableFrom(type))
                        _viewType2PresenterType.Add(args[0], type);
                }
            }
        }
    }
}
